package com.sunday.aomi.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sunday.common.base.BaseFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.common.widgets.dialog.ACProgressPie;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.aomi.R;
import com.sunday.aomi.adapter.OrderListAdapter;
import com.sunday.aomi.adapter.SellOrderListAdapter;
import com.sunday.aomi.entity.Driver;
import com.sunday.aomi.http.ApiClient;
import com.sunday.aomi.widgets.SelectDriverWindow;
import com.sunday.member.constv.ConstValue;
import com.sunday.member.entity.order.OrderItem;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static java.sql.DriverManager.getDrivers;

/**
 * Created by 刘涛 on 2017/6/6.
 */

public class SellOrderListFragment extends BaseFragment {

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private int type;
    private int statuses;
    private SellOrderListAdapter adapter;
    private List<OrderItem> dataSet = new ArrayList<>();

    public static SellOrderListFragment newInstance(int type, int statuses) {
        SellOrderListFragment fragment = new SellOrderListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putInt("statuses", statuses);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_order_list, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getInt("type", 0);
            statuses = getArguments().getInt("statuses");
        }
        initRecyclerView();
        getData();
    }


    private int lastVisibleItem = 1;
    private boolean isCanloadMore;
    private LinearLayoutManager layoutManager;
    private String sendOrderId;

    private void initRecyclerView() {
        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).drawable(R.drawable.horizontal_space_divider).build());
        adapter = new SellOrderListAdapter(mContext, dataSet);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo=1;
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo=1;
                getData();
            }
        });

        adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final OrderItem item = (OrderItem) v.getTag();
                sendOrderId = String.valueOf(item.getId());
                switch (v.getId()) {
                    case R.id.order_btn1:
                        //配送订单
                        if (item.getSendType()!=null&&item.getSendType() != 2) {
                            //选择配送员
                            getDriverList();
                        } else {
                            //直接配送
                            sendOrder(null);
                        }
                        break;
                    case R.id.item_view:
                        Intent intent = new Intent(mContext, SellOrderDetailActivity.class);
                        intent.putExtra("orderId", item.getId());
                        mContext.startActivity(intent);
                        break;
                }
            }
        });
    }

    private List<Driver> drivers = new ArrayList<>();

    private void getDriverList() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"nonce"};
        String[] str2 = new String[]{nonce};
        Call<ResultDO<List<Driver>>> call = ApiClient.getApiAdapter().getDriver(nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<List<Driver>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Driver>>> call, Response<ResultDO<List<Driver>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    drivers.clear();
                    drivers.addAll(response.body().getResult());
                }
                SelectDriverWindow driverWindow = new SelectDriverWindow(mContext, drivers);
                driverWindow.showPopupWindow(recyclerView);
                driverWindow.setOnSelectListner(new SelectDriverWindow.OnSelectListner() {
                    @Override
                    public void onSelect(int p) {
                        //配送
                        sendOrder(String.valueOf(drivers.get(p).getId()));
                    }
                });
            }

            @Override
            public void onFailure(Call<ResultDO<List<Driver>>> call, Throwable t) {

            }
        });
    }

    private void sendOrder(String driverId) {
        String nonce = MD5Utils.random();
        String[] str1 = null;
        String[] str2 = null;
        if (TextUtils.isEmpty(driverId)) {
            str1 = new String[]{"orderId", "nonce"};
            str2 = new String[]{sendOrderId, nonce};
        } else {
            str1 = new String[]{"orderId", "driverId", "nonce"};
            str2 = new String[]{sendOrderId, driverId, nonce};
        }
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().sendOrder(sendOrderId, driverId, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish||response.body()==null){return;}
                dissMissDialog();
                if (response.body().getCode()==0){
                    pageNo=1;
                    getData();
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
            }
        });
    }

    private int pageNo = 1;
    private int pageSize = 10;

    private void getData() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"type", "orderStatuses", "pageSize", "pageNumber", "nonce"};
        String[] str2 = new String[]{String.valueOf(type), String.valueOf(statuses), String.valueOf(pageNo), "10", nonce};
        Call<ResultDO<List<OrderItem>>> call = MemberClient.getApiAdapter().getOrderList(type, statuses,
                pageSize, pageNo, null, null, nonce,
                SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<List<OrderItem>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<OrderItem>>> call, Response<ResultDO<List<OrderItem>>> response) {
                ptrFrame.refreshComplete();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult());
                    if (dataSet.size() == 10) {
                        isCanloadMore = true;
                        pageNo++;
                    } else {
                        isCanloadMore = false;
                    }
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<OrderItem>>> call, Throwable t) {
                ptrFrame.refreshComplete();
                emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
